<?php

namespace app\common\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Order;
use app\admin\model\User;
use app\admin\model\user\Finance;
use app\admin\model\user\Recharge;
use app\admin\model\user\Statics;
use app\common\model\Config;
use think\Console;
use think\Db;
use think\Exception;

final class Payment
{
    private static $appId = '';
    private static $cusId = '';
    private static $apiUrl = "";
    private static $apiVersion = '12';
    private static $notifyUrl = '';
    private static $private_key = '';

    public function __construct()
    {
        self::$appId = "00322822";
        self::$cusId = "56350805912U8Z1";
        self::$apiUrl = "https://syb.allinpay.com/apiweb/h5unionpay/unionorder";//生产环境
//        self::$apiUrl = "https://syb-test.allinpay.com/apiweb/unitorder";//测试环境
        self::$notifyUrl = "https://app.guoshangufen.com/api/Productorder/notify";
        self::$private_key = 'MIIEogIBAAKCAQEAoO7nhIz+mX0uoJit4sZuEGASrjlkRD0CGld46nuZNBgCvgop/SeYD7g+tcFKmktOwm1hf/sfIdNKbJLcfD2OP4ChpQq4UWdfGwk5nC7yOyX4vtBwl6vtFuJdB1sNH4wZX6RfXPdRJEGyDV05AA0MaLWpPJcC4EjsBuG7YaM5+xm4bAB268blOSh5/vO3IARM0VCshqcGBw/U7XKpDK6e5zjF56iCwsPpOC6baWreb+MuLwkDvmDIEquzou+yWLuzYJlTbNwQhcK3S1ThNOlsfmE8EsfC0rJvmbCJqpu04sIGIYIFzvXUZB8Ey5WnzFW7wTD00QlHh6XI3/sHcCzcAQIDAQABAoIBABMbztxhp+zmbOIHgvUXcdPqrmkmuiGym0RwsLQp3RrvA2tYdlwfZoouSq7m3rJzoOxL080ADrYj2hVKeljbr79ZSQg5XcGXrDaf+anSdrNgerjAc/AEa2RBWEGydVxStKQTNroJiSZMkSVOVYFsqzWnJUtDFIW4TuMxzB+no4+tkaFqwUKh4U0jG0cCXimHOkm8p5CtUoYjgG/gvwj71wCoGdesVXBLuDtfi9dSrZx1D9TWfyPw5iojETl9ERWaYuSTb0PZvE0QRd0CW7JIHaZ7qbG61iebOJCfYqEJXPUOrjE657u2Esk0VhD0x2VrWWEMW31Jxpu5XuCgwvYjHhkCgYEA3adp6uN1qgB83JvfK41gX0LmcqMaWil8xVEjdSEEt6ITCpU8R4oqmqY8eHei1C+Fjw4axXmea/Ii9m3z5BcEpv5ZqP9Ova/Zsw28Cm6ZEAHw0JV9VkA+DfaMUM55cQTCSfAhCEUlaHkD4eJY2C9H5mAQy1mRqjnWm0WfaGAscakCgYEAud7Qz9B344Ca2ydCN+zAalsoWapoyycfCRFd6C+V84Ie1ePzFsUa7JaqcMkT5IeG0itJbdQuULoLisKYirDg3bHMMu3J2dbVQnU6f0UCpWSffbj5lL8eJV1y3WCQp5NQ4dfvJvHjpomhGK2sLPWN0Dv2smh4KBWO+W1ACZsmPpkCgYAyCrXy/d92vh1ygQ5lesmjOCtm/kPYzz0IH0VuEEJMYx8BaKfvTtZHi/hjCj+MwB3bKkgJBWgq3sPd9vz1Je069nmvmdRhJu5zakpl4IpV/torfVSKwH5CEMOlCriIN5bVso0CnPnRGGE0AjIkvKfy7wVbo6ErWVuGOrW+jtf54QKBgG5qYvlRCidn+pY92CSIzDViObIqfV5RuyoT2wlXW2jw34iIhZv9M2Vgi5e8m8iiigDIHjLUXT8vhjPELgIV2T9Zo8iNYd+6s61rHnkEcfH2uJhjDkDC2BGyVc4U01n5NY80S6mDAI2qLL0QTrvWk4wkUwTg8qA9TlX2BJiwRiPhAoGAIYn5AZD4ihFRmzFhsNWZQEUxBwty8BYntennU45exNs9NOaMuWGDUTeCXc05a3DFiot/ZCTlTMstdMGySRuWDTzCMqTdUxFqmxQI1Z/eAGm+adwxeNNqQcXdOnMbXKfk0/uwr+wrpkws/jfbBeo1UnoDvmu71bkIuckorJQb8P0=';
    }

    /**
     * 下单
     * @param $data
     * @return array
     */
    function pay($data)
    {
        $params = array();

        $params["cusid"] = self::$cusId;
        $params["appid"] = self::$appId;
        $params["version"] = self::$apiVersion;
//        $params["orgid"] = '';
        $params["trxamt"] = (string)($data['money'] * 100);//$data['money'];
        $params["reqsn"] = $data['order_no'];//$data['order_no'];
        $params["body"] = $data['body'];//$data['body'];
        $params["remark"] = $data['remark'];//$data['remark'];
//        $params["validtime"] = 12;//订单超时时间
//        $params["acct"] = 'oM4tN4x6Cdp51AYTZaYzPN2E8gLa';
//        $params["returl"] = 'https://app.guoshangufen.com/index/index/pay_success.html';
        $params["notify_url"] = self::$notifyUrl;
        $params["paytype"] = $data['paytype'];
//        $params["limit_pay"] = '';
//        $params["sub_appid"] = 'wx58959207ed2673ca';
//        $params["subbranch"] = '';
//        $params["cusip"] = '';
//        $params["idno"] = '';
//        $params["truename"] = '';
//        $params["fqnum"] = '';
//        $params["charset"] = 'UTF-8';
        $params["randomstr"] = '2d504c8637a2511231d8f35db1f5396d';
        $params["signtype"] = 'RSA';
//        $params["front_url"] = 'https://suppliershop.liancaiwang.cn/api/public/index.php/h5/pay/payApply';
//        var_dump($params);die;
        $params["sign"] = self::makeSign($params);//签名
//        $params["pay_url"] = self::$apiUrl;

        return $params;
    }


    //统一被扫接口
    function scanqrpay()
    {
        $params = array();
        $params["cusid"] = AppConfig::CUSID;
        $params["appid"] = AppConfig::APPID;
        $params["version"] = AppConfig::APIVERSION;
        $params["orgid"] = $orgid;
        $params["version"] = $version;
        $params["trxamt"] = $trxamt;
        $params["reqsn"] = $reqsn;
        $params["body"] = $body;
        $params["remark"] = $remark;
        $params["authcode"] = $authcode;
        $params["limit_pay"] = $limit_pay;
        $params["subbranch"] = $subbranch;
        $params["asinfo"] = $asinfo;
        $params["idno"] = $idno;
        $params["truename"] = $truename;
        $params["randomstr"] = $randomstr;
        $params["fqnum"] = $fqnum;
        $params["signtype"] = 'RSA';
        $params["sign"] = urlencode(AppUtil::Sign($params));//签名
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/pay";
        $rsp = request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (AppUtil::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
            echo "验签正确,进行业务处理";
        }

    }


//当天交易用撤销
    function cancel()
    {
        $params = array();
        $params["cusid"] = AppConfig::CUSID;
        $params["appid"] = AppConfig::APPID;
        $params["version"] = AppConfig::APIVERSION;
        $params["trxamt"] = "1";
        $params["reqsn"] = "123456788";
        $params["signtype"] = 'RSA';
        $params["oldreqsn"] = "123456";//原来订单号
        $params["randomstr"] = "1450432107647";//
        $params["sign"] = urlencode(AppUtil::Sign($params));//签名
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/cancel";
        $rsp = request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (AppUtil::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

//当天交易请用撤销,非当天交易才用此退货接口
    function refund()
    {
        $params = array();
        $params["cusid"] = AppConfig::CUSID;
        $params["appid"] = AppConfig::APPID;
        $params["version"] = AppConfig::APIVERSION;
        $params["trxamt"] = "1";
        $params["reqsn"] = "1234567889";
        $params["oldreqsn"] = "123456";//原来订单号
        $params["randomstr"] = "1450432107647";//
        $params["signtype"] = 'RSA';
        $params["sign"] = urlencode(AppUtil::Sign($params));//签名
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/refund";
        $rsp = request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (AppUtil::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

    function query()
    {
        $params = array();
        $params["cusid"] = AppConfig::CUSID;
        $params["appid"] = AppConfig::APPID;
        $params["version"] = AppConfig::APIVERSION;
        $params["reqsn"] = "123456";
        $params["randomstr"] = "1450432107647";//
        $params["signtype"] = 'RSA';
        $params["sign"] = urlencode(AppUtil::Sign($params));//签名
        $paramsStr = AppUtil::ToUrlParams($params);
        $url = AppConfig::APIURL . "/query";
        $rsp = request($url, $paramsStr);
        echo "请求返回:" . $rsp;
        echo "<br/>";
        $rspArray = json_decode($rsp, true);
        if (AppUtil::validSign($rspArray)) {
            echo "验签正确,进行业务处理";
        }
    }

//发送请求操作仅供参考,不为最佳实践
    function request($url, $params)
    {
        $ch = curl_init();
        $this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function httpRequest($url, $method, $postfields = null, $usejson = 0, $debug = false)
    {
        $method = strtoupper($method);
        $ci = curl_init();
        if ($usejson == 1) {//使用json提交方式需要加http头信息
            $headers = array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen(json_encode($postfields))
            );
        } else {
            $headers = array();
        }
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) curl ranjuan/20200400 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? self::ToUrlParams($postfields) : $postfields;
                    if ($usejson == 1) {
                        curl_setopt($ci, CURLOPT_POSTFIELDS, json_encode($postfields));
                    } else {
                        curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                    }
                }
                break;
            default:
                isset(explode('?', $url)[1]) ? ($url = $url . '&' . http_build_query($postfields)) : ($url = $url . '?' . http_build_query($postfields));
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
//curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
//        var_dump($response);die;
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "<br><br>=====" . $method . " data======" . $url . "\r\n<br>";
            var_dump($postfields);
            echo "<br><br>=====info===== \r\n<br>";
            print_r($requestinfo);
            echo "<br><br>=====response=====\r\n<br>";
            print_r($response);
        }
        curl_close($ci);
        return $response;
//return array($http_code, $response,$requestinfo);
    }


    //验签
    static function validSign($array)
    {
        $signRsp = strtolower($array["sign"]);
        $array["sign"] = "";
        $sign = strtolower(self::makeSign($array));

        var_dump($signRsp, $sign);
        die;
        if ($sign == $signRsp) {
            return TRUE;
        } else {
            echo "验签失败:" . $signRsp . "--" . $sign;
        }

        return FALSE;
    }

    /**
     * 将参数数组签名
     */
    private static function makeSign(array $array)
    {
        ksort($array);
        $bufSignSrc = self::ToUrlParams($array);
        write_log($bufSignSrc, 'sign');
        $private_key = self::$private_key;
        $private_key = chunk_split($private_key, 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($private_key) . "-----END RSA PRIVATE KEY-----";
        //   echo $key;
        if (openssl_sign($bufSignSrc, $signature, $key)) {
            //		echo 'sign success';
        } else {
            echo 'sign fail';
        }
        $sign = base64_encode($signature);//加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的

        return $sign;
    }

    private static function ToUrlParams(array $array)
    {
        $buff = "";
        foreach ($array as $k => $v) {
            if ($v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
}